<template>
  <el-row style="height:100%">
    <page>
      <pageheader :isShow="false">完善企业管理</pageheader>
      <div class="page-content">
        <el-card class="box-card">
          <el-steps :active="active" finish-status="success">
            <el-step title="新增企业"></el-step>
            <el-step title="新增控制角色"></el-step>
            <el-step title="新增数据角色"></el-step>
            <el-step title="新增用户"></el-step>
          </el-steps>
          <div v-show="active === 0">
            <el-form :model="enterpriseRuleForm" :rules="enterpriseRules" ref="enterpriseRuleForm" label-width="180px">
              <el-form-item label="企业名称" prop="company_name">
                <el-input v-model="enterpriseRuleForm.company_name" size="small" style="width:450px"></el-input>
              </el-form-item>
              <el-form-item label="所属企业" prop="parent_id_arr">
                <Cascader :value.sync="enterpriseRuleForm.parent_id_arr"
                          :options="options"
                          :changeEvent="'enterpriseChange'"
                          :width="'450px'"
                          :disabled="step_status > 0 ? true : false"></Cascader>
              </el-form-item>
              <el-form-item label="企业描述" prop="company_desc">
                <el-input v-model="enterpriseRuleForm.company_desc" type="textarea" size="small" :rows="3" style="width:450px"></el-input>
              </el-form-item>
            </el-form>
            <div class="dialog-footer">
              <el-button @click="back" size="small">返回</el-button>
              <el-button type="primary" size="small" @click="enterpriseConfirmDialog('enterpriseRuleForm')">下一步</el-button>
            </div>
          </div>
          <div v-show="active === 1">
            <el-form :model="roleControlRuleForm" :rules="roleControlRules" ref="roleControlRuleForm" label-width="180px">
              <el-form-item label="所属企业" prop="company_name">
                <el-input v-model="company_name" size="small" style="width:450px" readonly></el-input>
              </el-form-item>
              <el-form-item label="角色名称" prop="role_name">
                <el-input v-model="roleControlRuleForm.role_name" size="small" style="width:450px"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="role_desc">
                <el-input v-model="roleControlRuleForm.role_desc" type="textarea" size="small" style="width:450px"></el-input>
              </el-form-item>
              <el-form-item label="菜单选择">
                <el-button v-if="isRoot"
                           type="primary" size="small" @click="pushPower">快速配置运维工程师</el-button>
                <el-tree
                  :data="roleControlTreeData"
                  :default-checked-keys="roleControlRuleForm.menu_id_list"
                  :default-expanded-keys="roleControlRuleForm.menu_id_list"
                  node-key="id"
                  @check="roleControlClickCheck"
                  ref="roleControlTree"
                  :check-strictly="true"
                  :props="defaultProps"
                  show-checkbox>
                </el-tree>
              </el-form-item>
            </el-form>
            <div class="dialog-footer">
              <el-button @click="roleControlPreviousStep" size="small">上一步</el-button>
              <el-button type="primary" size="small" @click="roleControlConfirmDialog('roleControlRuleForm')">下一步</el-button>
            </div>
          </div>
          <div v-show="active === 2">
            <el-row>
              <el-form :model="roleDataRuleForm" :rules="roleDataRules" ref="roleDataRuleForm" label-width="150px">
                <el-form-item label="数据角色名称：" prop="org_auth_name">
                  <el-input v-model="roleDataRuleForm.org_auth_name" size="small" style="width:450px"></el-input>
                </el-form-item>
                <el-form-item label="组织架构：" prop="name">
                  <el-input  v-model="company_name" size="small" readonly style="width:450px"></el-input>
                </el-form-item>
<!--                <el-form-item label="数据指标：" prop="indicator_arr">-->
<!--                  <el-checkbox-group v-model="roleDataRuleForm.indicator_arr" size="small" @change="checkChange" style="width:80%">-->
<!--                    <el-checkbox v-for="item in regionList" :label="item.id" :key="item.id" border style="width: 120px; margin:10px 10px">{{item.name}}</el-checkbox>-->
<!--                  </el-checkbox-group>-->
<!--                </el-form-item>-->
                <el-form-item label="指标：" v-if="isShowRegionList" prop="indicator_arr">
                  <el-checkbox-group v-model="roleDataRuleForm.indicator_arr" size="small" @change="checkChange" style="width:80%">
                    <el-checkbox v-for="item in regionList" v-if="item.type == 1"
                                 :label="item.key" :key="item.key" border style="width: 120px; margin:10px 10px">
                      {{item.name}}
                      <el-popover v-if="item.desc" placement="right-start" title="说明:" width="300" trigger="hover"
                                  :content="item.desc">
                        <i slot="reference" class="el-icon-question"></i>
                      </el-popover>
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="人脸指标：" v-if="isShowRegionListFace" prop="indicator_arr_face">
                  <el-checkbox-group v-model="roleDataRuleForm.indicator_arr_face" size="small" @change="faceCheckChange" style="width:80%">
                    <el-checkbox v-for="item in regionList" v-if="item.type == 2"
                                 :label="item.key" :key="item.key" border style="width: 120px; margin:10px 10px">
                      {{item.name}}
                      <el-popover v-if="item.desc" placement="right-start" title="说明:" width="300" trigger="hover"
                                  :content="item.desc">
                        <i slot="reference" class="el-icon-question"></i>
                      </el-popover>
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="指标：" v-if="!isShowRegionList && !isShowRegionListFace">
                  <span style="color:#ccc;">该权限下指标为空</span>
                </el-form-item>
              </el-form>
            </el-row>
            <div class="dialog-footer">
              <el-button @click="roleDataPreviousStep" size="small">上一步</el-button>
              <el-button type="primary" size="small" @click="roleDataConfirmDialog('roleDataRuleForm')">下一步</el-button>
            </div>
          </div>
          <div v-show="active === 3">
            <el-form :model="userRuleForm" :rules="userRules" ref="userRuleForm" label-width="180px">
              <el-form-item label="企业名称" prop="company_name">
                <el-input v-model="company_name" size="small" style="width:450px" readonly></el-input>
              </el-form-item>
              <el-form-item label="用户名" prop="user_name">
                <el-input v-model="userRuleForm.user_name" size="small" style="width:450px"></el-input>
              </el-form-item>
              <el-form-item label="输入密码" prop="user_pwd">
                <el-input v-model="userRuleForm.user_pwd" show-password size="small" style="width:450px" maxlength="20"></el-input>
              </el-form-item>
              <el-form-item label="再次输入密码" prop="user_pwd_again">
                <el-input v-model="userRuleForm.user_pwd_again" show-password size="small" style="width:450px" maxlength="20"></el-input>
              </el-form-item>
            </el-form>
            <div class="dialog-footer">
              <el-button @click="userPreviousStep" size="small">上一步</el-button>
              <el-button type="primary" size="small" @click="userConfirmDialog('userRuleForm')">完成</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </page>
  </el-row>
</template>

<script>
  import page from "@/components/page/page";
  import pageheader from "@/components/page/pageheader";
  import Cascader from "@/components/sys/assembly/elcascader";
  import reportGlobal from "@/components/global/reportGlobal";//公共配置

  const menu_id_list = reportGlobal.menu_id_list
  export default {
    data() {
      let validateCompanyName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入企业名称'));
        } else {
          let str =  /[`~!@#$%^&*\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*\-+={}|《》？：“”【】、；‘’，。、]/im;
          if(str.test(value)){
            return callback(new Error('企业名称不得使用特殊符号！'));
          }
          if(value.length >=30){
            return callback(new Error('企业名称长度不能超过30个字！'));
          }
          callback();
        }
      };
      let validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.userRuleForm.user_pwd_again !== '') {
            this.$refs.userRuleForm.validateField('user_pwd_again');
          }
          callback();
        }
      };
      let validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.userRuleForm.user_pwd) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      //案场编码表单校验，判断案场编码是否存在
      let validateUserName = (rule, value, callback)=>{
        if (!value) {
          return callback(new Error('用户名不能为空'));
        }else{
          let str = /^[a-z][a-z0-9_]+$/
          if(!str.test(value)){
            return callback(new Error('用户名只能输入小写英文，数字和下滑线,且第一位必须为字母'));
          }
        }
        let url = '/sys/user/exist_username?user_name='+ value;
        this.$api.post(url)
        .then(data =>{
          if(data.data){
            callback(new Error('用户名已存在'));
          }else{
            callback();
          }
        })
      }
      return {
        step_status:0,//该新增企业最高步骤数（用来判断进入某一步骤时是否需要调用GET接口）
        active: 0,//当前页面显示步骤
        options:[],//级联控件 所属企业
        company_id:'',//企业id
        company_name:'',//企业名称;

        //step1;新增企业
        enterpriseRuleForm:{
          company_name:'',
          parent_id:'',
          parent_id_arr:'',
          company_desc:'',
        },//企业form表单
        enterpriseRules: {
          company_name: [{ required: true, validator:validateCompanyName, trigger: "blur"}],
        },//企业form表单验证

        //step2;新增控制角色
        roleControlRuleForm:{
          role_name:'菜单权限管理员',
          role_desc:'',
          menu_id_list:[],
        },//控制角色管理form表单
        roleControlRules:{
          role_name:[{ required: true, message: "请输入角色名称", trigger: "blur"}]
        },
        defaultProps:{
          label: 'menu_name',
        },//树形控件配置选项
        roleControlTreeData:[],

        //step3;新增数据角色
        roleDataRuleForm:{
          org_auth_name:'数据权限管理员',
          indicator_arr:[],
          indicator_str:'',
          indicator_str_face:'',
          indicator_arr_face:[],
        },
        roleDataRules:{
          org_auth_name: [{ required: true, message: "请输入数据角色名称", trigger: "blur"}],
        },
        regionList:[],//区域权限list
        roleDataProps: {
          value: 'value',
          label: 'name',
          children: 'children'
        },
        isShowRegionList:false,
        isShowRegionListFace:false,

        //step4;新增用户
        userRuleForm:{
          user_name:'',
          user_pwd:'',
          user_pwd_again:'',
        },
        userRules:{
          user_name:[
            { required: true, validator:validateUserName, trigger: "blur"},
          ],
          user_pwd: [
            { required: true, validator:validatePass, trigger: "blur"},
            { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur"}
          ],
          user_pwd_again: [
            { required: true, validator:validatePass2, trigger: "blur"},
            { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur"}
          ],
        },
        isRoot:false,//是否是管理员
        isDisabled:false,//是否禁止选择所属企业
      }

    },
    components:{
      page,
      pageheader,
      Cascader,//级联选择器组件
    },
    created(){
      this.step_status = this.$route.params.active ? this.$route.params.active : 0;
      this.active = this.$route.params.active ? this.$route.params.active : 0;
      this.company_id = this.$route.params.id ? this.$route.params.id : '';
      this.company_name = this.$route.params.company_name ? this.$route.params.company_name : '';
      if(localStorage.isRoot){
        this.isRoot = localStorage.isRoot == 1 ? true :false
      }
      this.getTree();

    },
    mounted(){
      //级联change事件
      this.$Bus.$on("enterpriseChange", data => {
        this.enterpriseRuleForm.parent_id_arr = data
        this.enterpriseRuleForm.parent_id = data.slice(-1)[0]
      });
    },
    beforeDestroy(){
      this.$Bus.$off("enterpriseChange")
    },
    watch:{
      active(val) {
        switch (val) {
          case 0:
            if (this.step_status > val) {
              let url = '/sys/company/get?id=' + this.company_id
              this.$api.get(url)
              .then(data => {
                if(data == '10001'){
                  this.$message.error('无权操作该数据')
                  return
                }
                if (data) {
                  let _data = data.data
                  _data.parent_id_arr = _data.node_location.split('-');
                  _data.parent_id_arr.splice(-2, 2);
                  this.enterpriseRuleForm = Object.assign(this.enterpriseRuleForm, _data)
                }
              })
            }
            break;
          case 1:
            this.getAuthTree();
            if(this.step_status > val){
              let url = '/sys/init_company/step2?company_id=' + this.company_id
              this.$api.get(url)
              .then(data => {
                if(data == '10001'){
                  this.$message.error('无权操作该数据')
                  return
                }
                if (data) {
                  let _data = data.data
                  this.roleControlRuleForm.role_desc = _data.role_desc
                  this.roleControlRuleForm.menu_id_list = _data.menu_id_list
                }
              })
              .catch(err=>{
                 console.log(err);
              })
            }
            break;
          case 2:
            this.getOrgAuthIndicators();
            break;
        }
      }
    },
    methods:{
      /*
      企业管理
       */
      //获取企业tree
      getTree(){
        let url = '/sys/report_assist_new/company_tree';
        this.$api.get(url)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            return
          }
          if(data){
            recursion(data.data);
            function recursion(val) {
              if(val.length){
                for(let i in val){
                  val[i].value = val[i].id;
                  val[i].label = val[i].company_name;
                  val[i].parent_id_str = val[i].parent_name_list.join('/');
                  if(val[i].children && val[i].children.length){
                    recursion(val[i].children)
                  }else{
                    delete val[i].children
                  }
                }
              }
            }
            this.options = data.data
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },
      //模态框保存按钮
      enterpriseConfirmDialog(formName) {
        let data = {};
        let model = null;
        let url = ''
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.$Bus.$emit('Loading',true)
            model = this.$refs[formName].model;
            //判断是否为第一新增企业，如果active < step_status时调用修改接口
            if (this.active < this.step_status) {
              data.company_desc = model.company_desc
              data.company_name = model.company_name
              url = "/sys/company/update?id=" + this.company_id;
              this.$api.put(url,data)
              .then(data=>{
                if(data == '10001'){
                  this.$message.error('无权操作该数据')
                  return
                }
                if(data){
                  this.company_name = model.company_name;
                  this.active++;//跳转到下一页
                }
                this.$Bus.$emit('Loading',false)
              })
            } else {
              data.company_desc = model.company_desc
              data.company_name = model.company_name
              data.parent_id = model.parent_id
              url = "sys/init_company/step1";
              this.$api.post(url, data)
              .then(data => {
                if(data == '10001'){
                  this.$message.error('无权操作该数据')
                  return
                }
                if(data){
                  this.company_id = data.data
                  this.company_name = model.company_name;
                  this.active++;//跳转到下一页
                  this.step_status++;//新增企业最高步骤加一
                }
                this.$Bus.$emit('Loading',false)
              })
            }
          } else {
            console.log("error submit!!");
            return;
          }
        });
      },
      //修改保存
      modifyCompany(url,data){
        this.$api
        .put(url, data)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            return
          }
          if(data){
            this.reload();
            this.$message({
              message: "修改成功",
              type: "success"
            });
          }
          this.$Bus.$emit('Loading',false)
        })
      },
      //返回按钮
      back(){
        this.$confirm('填写数据还未完成，是否确定返回？','提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center:true
        }).then(() => {
          this.$router.go(-1)
        }).catch(() => {
        });
      },
      /*
      控制角色管理
       */
      //获取用户菜单列表
      getAuthTree(){
        let url = '/sys/menu/auth_tree'
        this.$api.get(url)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            return
          }
          if(data){
            if(this.isRoot) {
              // console.log('isRoot');
              for (let i in data.data) {
                if (data.data[i].menu_url == 'realTimeChain') data.data[i].menu_name = '实时数据驾驶舱(连锁店)'
                if (data.data[i].menu_url == 'realTimeMall') data.data[i].menu_name = '实时数据驾驶舱(购物中心)'
              }
            }
            this.roleControlTreeData = data.data
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.roleControlTreeData = []
          this.$Bus.$emit('Loading',false)
        })
      },
      //tree结构的复选框实现子集选中时选中所有父级，子集取消时取消所有子级
      roleControlClickCheck(data,checkedKeys){
        let parentArr = [];
        //找到子集并选中他们
        let openChildrens = arr =>{
          parentArr = data.node_location.split('-')
          parentArr.forEach(x=>{
            this.$refs.roleControlTree.setChecked(x,true);
          })
          for(let i in arr.children){
            this.$refs.roleControlTree.setChecked(arr.children[i].id,true);
            if(arr.children[i].children != 0){
              openChildrens(arr.children[i])
            }
          }
        };
        let clearChildrens = arr =>{
          for(let i in arr.children){
            this.$refs.roleControlTree.setChecked(arr.children[i].id,false);
            if(arr.children[i].children != 0){
              clearChildrens(arr.children[i])
            }
          }
        }
        if(checkedKeys.checkedKeys.includes(data.id)){
          openChildrens(data)
        }else{
          //当点击tree为取消状态，则通过clearChildrens方法，找到子集并取消他们
          clearChildrens(data)
        }
      },

      //新增数据角色下一步
      roleControlConfirmDialog(formName){
        let data = {};
        let model = null;
        let url = ''
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.$Bus.$emit('Loading',true)
            model = this.$refs[formName].model;

              data.company_id = this.company_id
              data.menu_id_list = this.$refs.roleControlTree.getCheckedKeys()
              data.role_desc = model.role_desc
              data.role_name  = model.role_name;

              url = "sys/init_company/step2?company_id="+data.company_id;
              this.$api.post(url, data)
              .then(data => {
                this.$Bus.$emit('Loading', false)
                if (this.active >= this.step_status) {
                  this.step_status++;//新增企业最高步骤加一
                }
                this.active++//跳转到下一页
              })
              //this.addCompany(url, data);
          } else {
            console.log("error submit!!");
            return;
          }
        });
      },
   
      //控制角色管理上一步
      roleControlPreviousStep(){
        this.active = 0;
      },

      /*
      数据角色管理
       */
      //表格checkbox的获取值
      checkChange(value){
        this.roleDataRuleForm.indicator_str = value.join(',')
      },

      //获取可使用指标列表
      getOrgAuthIndicators(){
        let url = '/sys/org_auth/indicators?org_type=1&foreign_key=' + this.company_id;
        this.$api.get(url)
        .then(data =>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            return
          }
          if(data){
            this.regionList = data.data
            let arr = this.regionList.filter(x=>x.type == 1)
            let arr_face = this.regionList.filter(x=>x.type == 2)
            this.isShowRegionList = arr.length ? true :false
            this.isShowRegionListFace = arr_face.length ? true :false

            if(this.step_status > this.active){
              let url = '/sys/init_company/step3?company_id=' + this.company_id;
              this.$api.get(url)
              .then(data2 => {
                if(data2 == '10001'){
                  this.$message.error('无权操作该数据')
                  return
                }
                if (data2) {
                  let indicator_arr = data2.data.indicator_str.split(',')
                  let indicator_list = [];//普通指标数组
                  let indicator_list_face = [];//人脸指标数组
                  for(let i in indicator_arr){
                    for(let j in this.regionList){
                      if(this.regionList[j].id == indicator_arr[i]){
                        //根据type分别push不同指标到对应数组
                        if(this.regionList[j].type == 1) indicator_list.push(this.regionList[j])
                        if(this.regionList[j].type == 2) indicator_list_face.push(this.regionList[j])
                      }
                    }
                  }
                  this.roleDataRuleForm.indicator_arr = indicator_list.map(x=>x.key)
                  this.roleDataRuleForm.indicator_arr_face = indicator_list_face.map(x=>x.key)
                  this.roleDataRuleForm.indicator_str =indicator_list.map(x=>x.id).join(',')
                  this.roleDataRuleForm.indicator_str_face = indicator_list_face.map(x=>x.id).join(',')
                }
              })
            }
            this.$Bus.$emit('Loading',false)
          }
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },
      //数据角色管理上一步
      roleDataPreviousStep(){
        this.active = 1;
      },
      //数据角色管理下一步
      roleDataConfirmDialog(formName) {
        let model = null;
        let url = ''
        this.$refs[formName].validate(valid => {
          if (valid) {
            if((this.roleDataRuleForm.indicator_arr.length == 0 && this.roleDataRuleForm.indicator_arr_face.length == 0)){
              this.$message.error('请选择数据指标')
              return
            }
            this.$Bus.$emit('Loading', true)
            model = this.$refs[formName].model;
            let indicator_arr = [...this.roleDataRuleForm.indicator_str.split(','),...this.roleDataRuleForm.indicator_str_face.split(',')].join(',')
            console.log(indicator_arr,'indicator_arr');
            url = "sys/init_company/step3?company_id=" + this.company_id + '&indicator_str=' + indicator_arr + '&org_auth_name=' + model.org_auth_name;
            this.$api.post(url)
            .then(data => {
              if(data == '10001'){
                this.$message.error('无权操作该数据')
                return
              }
              if (data) {
                if (this.active >= this.step_status) {
                  this.step_status++;//新增企业最高步骤加一
                }
                this.active++//跳转到下一页
              }
              this.$Bus.$emit('Loading', false)
            })
          } else {
            console.log("error submit!!");
            return;
          }
        });
      },
      //多选的change
      checkChange(value){
        let indicator_str = []
        for(let i in this.regionList){
          if(value.includes(this.regionList[i].key)){
            indicator_str.push(this.regionList[i].id)
          }
        }
        this.roleDataRuleForm.indicator_str = indicator_str.join(',')
      },
      //多选的change
      faceCheckChange(value){
        let indicator_str = []
        for(let i in this.regionList){
          if(value.includes(this.regionList[i].key)){
            indicator_str.push(this.regionList[i].id)
          }
        }
        this.roleDataRuleForm.indicator_str_face = indicator_str.join(',')
      },
      /*
      用户管理
       */
      //用户上一步
      userPreviousStep(){
        this.active = 2
      },
      userConfirmDialog(formName) {
        let data = {};
        let model = null;
        let url = ''
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.$Bus.$emit('Loading', true)
            model = this.$refs[formName].model;
            if (this.isDisabled) {
              data.company_desc = model.company_desc
              data.company_name = model.company_name
              url = "sys/company/update?id=" + model.id;
              this.modifyCompany(url, data);
            } else {
              url = "sys/init_company/step4?company_id=" + this.company_id + '&username=' + model.user_name + '&password=' + model.user_pwd;
              this.$api.post(url, data)
              .then(data => {
                if(data == '10001'){
                  this.$message.error('无权操作该数据')
                  this.$Bus.$emit('Loading', false);
                  return
                }
                if (data) {
                  this.$Bus.$emit('Loading', false);
                  if (data.msg == 'success')
                    this.$message({
                      type: 'success',
                      message: '保存成功!'
                    });
                  this.$router.push('enterprisemanager')   //跳转到菜单页
                }
              })
              //this.addCompany(url, data);
            }
          } else {
            console.log("error submit!!");
            return;
          }
        });
      },
      //快速配置运维工程师
      pushPower(){
        this.$set(this.roleControlRuleForm,'menu_id_list',menu_id_list)
      }
    }
  }
</script>

<style scoped lang="scss">
  .page-content {
    padding: 15px;
    .fr {
      float: right;
    }
    .el-table {
      margin-bottom: 10px;
    }
    .paging {
      margin: 15px;
      height: 28px;
    }
  }
  .dialog-footer{
    text-align: right;
  }
</style>